# 导包
import pymysql
import config

# 创建类
class SQLUtil():
    __conn = None
    __cursor = None

    # 类方法：创建连接
    @classmethod
    def __getConn(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(host=config.SQL_data[0], port=config.SQL_data[1], user=config.SQL_data[2], password=config.SQL_data[3],
                                         database=config.SQL_data[4])
        return cls.__conn

    # 创建游标
    @classmethod
    def __getCursor(cls):
        if cls.__cursor is None:
            cls.__cursor = cls.__getConn().cursor()
        return cls.__cursor

    # 执行sql
    @classmethod
    def executeSQL(cls, sql):
        try:
            cursor = cls.__getCursor()
            cursor.execute(sql)
            if sql.split()[0].lower() == "select":
                return cursor.fetchall()
            else:
                cls.__getConn().commit()
                return cursor.rowcount

        except Exception as e:
            cls.__getConn().rollback()
            print(f"Error:{e}")

        finally:
            cls.__closeCursor()
            cls.__closeConn()

    # 关闭游标
    @classmethod
    def __closeCursor(cls):
        if cls.__cursor:
            cls.__cursor.close()
            cls.__cursor = None

    # 关闭链接
    @classmethod
    def __closeConn(cls):
        if cls.__conn:
            cls.__conn.close()
            cls.__conn = None
